﻿#include "menuservice.h"

#include <coredatabase.h>
#include <menudao.h>

MenuService::MenuService(QObject *parent) : QObject(parent)
{
    db = CoreDatabase::getInstance()->getConnection();
}

MenuService::~MenuService()
{
    CoreDatabase::getInstance()->releaseConnection(db);
}

bool MenuService::getVOListByParentId(QList<MenuVO> &list, uint64_t parentId)
{
    bool res = false;
    MenuDao objectDao(db);
    QList<Menu> menuList;
    if (objectDao.getListByParentId(menuList,parentId))
    {
        res = true;
        for(Menu &menuTmp:menuList){
            MenuVO menuVO;
            menuVO.fromMenu(menuTmp);
            QList<MenuVO> children;
            getVOListByParentId(children,menuTmp.getId());
            menuVO.setChildren(children);

            list.append(menuVO);
        }
    }
    return res;
}

//判断是否存在交集
bool hasCommonElements(const QStringList &list1, const QStringList &list2) {
    foreach (const QString &item, list1) {
        if (list2.contains(item)) {
            return true;
        }
    }
    return false;
}

bool MenuService::getVOListByAuthAndParentId(QList<MenuVO> &list, QStringList auths, uint64_t parentId)
{
    bool res = false;
    MenuDao objectDao(db);
    QList<Menu> menuList;
    if (objectDao.getListByParentId(menuList,parentId))
    {
        res = true;
        for(Menu &menuTmp:menuList){
            MenuVO menuVO;
            menuVO.fromMenu(menuTmp);
            QList<MenuVO> children;
            getVOListByAuthAndParentId(children,auths,menuTmp.getId());
            menuVO.setChildren(children);
            //权限判断
            if(hasCommonElements(auths,menuVO.getMeta().getAuthority())){
                list.append(menuVO);
            }
        }
    }
    return res;
}

bool MenuService::getVOListBYAuth(QList<MenuVO> &list, QStringList auths)
{
    return getVOListByAuthAndParentId(list,auths,0);
}

bool MenuService::getList(QList<Menu> &list)
{
    MenuDao objectDao(db);
    return objectDao.getList(list);
}

bool MenuService::getOne(Menu &object)
{
    MenuDao objectDao(db);
    return objectDao.getOne(object);
}

bool MenuService::saveOne(Menu &object)
{
    MenuDao objectDao(db);
    return objectDao.saveOne(object);
}

bool MenuService::deleteOne(Menu &object)
{
    MenuDao objectDao(db);
    return objectDao.deleteOne(object);
}
